package com.maikec.utils.jwt;
/**
 * 邢帅教育
 * <p>
 * 本源代码由数据中心及其作者共同所有，未经版权持有者的事先书面授权，
 * 不得使用、复制、修改、合并、发布、分发和/或销售本源代码的副本。
 *
 * @copyright Copyright (c) 2018. [图片]xsteach.com all rights reserved.
 */

import cn.hutool.core.util.ArrayUtil;
import com.maikec.configure.JwtConfig;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author maikec
 * @date 2018/7/25
 */
public class JwtFilter extends OncePerRequestFilter {
    private static Logger logger = LoggerFactory.getLogger(JwtFilter.class);

    @Override
    public void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
        logger.info(req.getHeader("Authorization"));
        if (HttpMethod.OPTIONS.matches(req.getMethod())
                || ArrayUtil.contains(JwtConfig.getPermitUrl(), req.getRequestURI())
                || !JwtConfig.getIsProd()) {
            chain.doFilter(req, res);
            return;
        }
        try {
            JwtFactory.getInstance().checkToken(req.getHeader("Authorization"));
            chain.doFilter(req, res);
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            res.setStatus(HttpStatus.REQUEST_TIMEOUT.value());
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
            res.setStatus(HttpStatus.UNAUTHORIZED.value());
        } catch (SignatureException e) {
            e.printStackTrace();
            res.setStatus(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED.value());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            res.setStatus(HttpStatus.BAD_REQUEST.value());
        }
    }
}
